﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Windows.Forms;
using Fleck;

namespace ComTools
{
    public partial class frmWebApi : Form
	{
		public frmWebApi()
		{
			InitializeComponent();
		}

		Socket sockerServer = null;
		HttpSelfHostConfiguration config = null;
		HttpSelfHostServer server = null;
		private void StartWebapiHost()
		{
			string url = $"http://{txtIP.Text}:{txtPort.Text}";

			config = new HttpSelfHostConfiguration(url);
			config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new
                {
                    controller = "receive",
                    action = "get",
                    id = RouteParameter.Optional
                }
            );
            server = new HttpSelfHostServer(config);
			//server必须以管理员身份启动
			server.OpenAsync().Wait();
            //
            OutputLine($"webapi service has started at {url}");
		}

		private void StartSocketServer()
		{
			sockerServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			sockerServer.Bind(new IPEndPoint(IPAddress.Any, 65500));
			sockerServer.Listen(10);
			sockerServer.BeginAccept(ServerAccept, sockerServer);
		}

		private void ServerAccept(IAsyncResult iasr)
		{
			Socket server = iasr.AsyncState as Socket;
			Socket client = server.EndAccept(iasr);
			//
			server.BeginAccept(ServerAccept, server);
			//
			byte[] data = new byte[2048];
			client.BeginReceive(data, 0, data.Length, SocketFlags.None, ServerReceive,
				new Tuple<Socket, byte[]>(client, data));
		}

		private void ServerReceive(IAsyncResult iasr)
		{
			Tuple<Socket, byte[]> tuple = iasr.AsyncState as Tuple<Socket, byte[]>;
			Socket client = tuple.Item1;
			byte[] temp = tuple.Item2;
			int len = client.EndReceive(iasr);
			if (len > 0)
			{
                byte[] data = new byte[len];
                Array.Copy(temp, data, len);
                //OutputLine(BitConverter.ToString(data));
                OutputLine(Encoding.Unicode.GetString(data, 0, len));
			}
			//
			temp = new byte[2048];
			client.BeginReceive(temp, 0, temp.Length, SocketFlags.None, ServerReceive, 
				new Tuple<Socket, byte[]>(client, temp));
		}

		Action<string> actionOutput = null;
		private void Output(string msg)
		{
			if (actionOutput == null)
			{
				actionOutput = new Action<string>((txt) =>
				{
					richTextBox1.AppendText(msg);
				});
			}
			richTextBox1.BeginInvoke(actionOutput, msg);
		}

		private void OutputLine(string msg)
		{
			Output(msg + Environment.NewLine);
		}

		private void btnStart_Click(object sender, EventArgs e)
		{
			StartWebapiHost();
		}

		private void btnStop_Click(object sender, EventArgs e)
		{
			if (server != null)
			{
				server.CloseAsync().Wait();
				server.Dispose();
				OutputLine("webapi service has stoped");
			}
		}

        private void frmWebApi_Load(object sender, EventArgs e)
        {
			//StartSocketServer();
		}
    }
}